/**
 * 连雷明 19.11.06修改
 * 99行，给方法selectLocation，加参数 HttpSession session
 * 121-124行，在方法selectLocation中，获取session中的仓库ID，存入map
 * 396行，给方法addInventoryOrder，加参数 HttpSession session
 * 410-417行， 方法addInventoryOrder中，获取session中的仓库ID，存入数据库
 * 646-652行， 给方法queryInventoryOrderCriteriaAndroid，加参数 warehouse_id, 并传值，分页查询盘点单
 *  
 */
package com.sdry.web.controller.lz;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.lz.InventoryDetail;
import com.sdry.model.lz.InventoryDetailCode;
import com.sdry.model.lz.InventoryOrder;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.lz.WarehouseRegionLocation;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcMaterileMoveInfoEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.lz.CarService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.Page;
import com.sdry.utils.ResponseUtil;
import com.sdry.web.controller.cb.BaseController;
import com.sdry.web.controller.jyy.unpack.JyyInfoGood;
import com.sdry.web.controller.llm.LoggerController;

/**
 * @ClassName InventoryController
 * @Description 盘点管理
 * @Author lz
 * @Date 2019年3月26日 14:17:05
 * @Version 1.0
 */
@Controller
@RequestMapping("/inventory")
public class InventoryController extends LoggerController{

	private static final long serialVersionUID = 1L;

	public static final Integer AFFECT_ROW = 0;
	
	@Resource
	/**盘点业务层接口*/
	InventoryService inventoryService;
	@Resource
	/**物料业务层接口*/
	MaterielService materielService;
	@Resource
	BarCodeOperationService barCodeOperationService;
	@Resource
	ZcBindAndUnbindService zcBindAndUnbindService;
	@Resource
	ReceiveDetailService receiveDetailService;
	@Resource
	CarService carService;

	/**
	 * 根据库位、物料、供应商等条件查询库位
	 * @param location 库位、
	 * @param materiel_num 物料
	 * @param customer 供应商
	 */
	@RequestMapping("/selectLocation")
	public void selectLocation(String location, String materiel_num, String customer, HttpServletResponse response, HttpSession session) {
		
		Map<String, Object> map = new HashMap<>();
		if (location != null && !"" .equals(location)) {
			map.put("location", location);
		} else {
			map.put("location", "");
		}
		if (customer != null && !"".equals(customer)) {
			map.put("customer",customer);
		} else {
			map.put("customer", "");
		}
		
		if(null != materiel_num){
			String [] split = materiel_num.split(",");
			for(int i = 0; i < split.length; i ++){
				map.put("key"+i, split[i].trim());
			}
		}else{
			map.put("key0", "");
		}
		//------------ llm start------------
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		map.put("warehouse_id", warehouse_id);
		//------------ llm end------------
		//多条件查询库位
		List<WarehouseRegionLocation> list = inventoryService.selectLocation(map);
		
		JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(list);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", list.size());
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 盘点单确认
	 * @author jyy
	 * @param inventoryOrder 盘点单实体
	 * @param response 响应
	 * @param session 会话信息
	 */
	@RequestMapping("/confirm")
	public void confirm(InventoryOrder inventoryOrder, HttpServletResponse response, HttpSession session) {
		
		int aff = 0;
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//确认时间
		inventoryOrder.setConfirmed_time(sdf.format(new Date()));
		//盘点单状态：3：已确认
		inventoryOrder.setTab("3");
		//获取session信息
		ZcSysUserEntity user = (ZcSysUserEntity)session.getAttribute("user");
		//确认人id
		inventoryOrder.setConfirmed_man(user.getId());
		//一：修改盘点单的确认人、时间、状态等信息
		aff = inventoryService.update(inventoryOrder);
		
		
		//二 ：把有差异的条码移到损益区
		//1、查询所有有差异的条码
		List<InventoryDetailCode> list = inventoryService.queryCodeByDiff(inventoryOrder.getId());
		//2、把有差异的条码转移到损益区
		for(InventoryDetailCode code : list){
			String addStr = "";
			//（1）.通过条码，在物料托盘绑定表（zc_materiel_tray）中找到该条码所在记录的id
			 //根据原条码查询绑定托盘的信息
            ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = receiveDetailService.queryMaterielTrayByCode(code.getCode());
            if(zcMaterielAndTrayEntity != null) {
            	if(zcMaterielAndTrayEntity.getTray_code() != null) {
            		 //根据托盘查询库位信息
                    ZcTrayAndLocationEntity zcTrayAndLocationEntity = receiveDetailService.queryTrayLocationByTray(zcMaterielAndTrayEntity.getTray_code());
                    
                    if(zcTrayAndLocationEntity != null) {
                    	//（2）.通过id用  空字符串   替换 条码+“，”
                        zcMaterielAndTrayEntity.setSrcRegion(code.getCode()+",");
                        zcMaterielAndTrayEntity.setTargetRegion("");
                        
                        //根据条码查询该条码在库存中的数量
                        int num = inventoryService.selectNumByCode(code.getCode());
                        
                        zcMaterielAndTrayEntity.setmNum(zcMaterielAndTrayEntity.getmNum() - num );
                        
                        //在物料托盘绑定表中去掉此物料条码
                        aff = carService.updateCodeByid(zcMaterielAndTrayEntity);
                        
                        String materiel_code = zcMaterielAndTrayEntity.getMateriel_code();
                        String replace = materiel_code.replace(code.getCode()+",", "");
                        
                        if(replace.length() == 0) {
                        	 //在托盘库位表中去掉此托盘条码
                            zcTrayAndLocationEntity.setTray_code(zcMaterielAndTrayEntity.getTray_code()+",");
                            aff = carService.updateTrayCodeByid(zcTrayAndLocationEntity);
                        }
                        
                        //查询此托盘还有没有条码，没有则删除
                        inventoryService.deleteEmptyTray();
                        
                        //(3).生成一个逻辑托盘码
                		String tray_code = System.currentTimeMillis()+"";
                		//（4）.在物料-托盘绑定表中新增一条记录
            	    		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity2 = new ZcMaterielAndTrayEntity();
            	    		//物料id
            	    		zcMaterielAndTrayEntity2.setMid(zcMaterielAndTrayEntity.getMid());
            	    		//pici
            	    		zcMaterielAndTrayEntity2.setmBatch(zcMaterielAndTrayEntity.getmBatch());
            	    		//所有条码
            	    		zcMaterielAndTrayEntity2.setMateriel_code(code.getCode()+",");
            	    		//托盘码
            	    		zcMaterielAndTrayEntity2.setTray_code(tray_code);
            	    		//条码的账面数量
            	    		zcMaterielAndTrayEntity2.setmNum(num);
            	    		//绑定人
            	    		zcMaterielAndTrayEntity2.setBinding_person(user.getId());
            	    		//绑定时间
            	    		zcMaterielAndTrayEntity2.setBinding_date(sdf.format(new Date()));
            	    		
            	    		//在物料托盘绑定表中新增一条记录
            	    		aff = inventoryService.MaterielTrayInsert(zcMaterielAndTrayEntity2);
            	    		
            	    		//（5）判断原物料在哪个库存，在原库存表中将数量减去
            	    		String location_code = zcTrayAndLocationEntity.getLocation_code();
            	    		
            	    		if("HC".equals(location_code)) {
            	    			aff =inventoryService.hcDown(zcMaterielAndTrayEntity2);
            	    		}else if("DJ".equals(location_code)){
            	    			aff =inventoryService.djDown(zcMaterielAndTrayEntity2);
            	    		}else {
            	    			aff =inventoryService.goodDown(zcMaterielAndTrayEntity2);
            	    		}
            	    		
            	    		//(6)在损溢表中添加一条记录
            	    		zcMaterielAndTrayEntity2.setmNum(code.getTheory_num());
            	    		aff = inventoryService.insertProfitLoss(zcMaterielAndTrayEntity2);
    	            		addStr += tray_code + ",";
    	        		}
            		
    	        		//（7）.在托盘-库位绑定表（zc_tray_location）中找是否存在 损溢区“SY”的记录
    	        		ZcTrayAndLocationEntity zcTrayAndLocationEntity2 = inventoryService.selectTrayLocationByLocationCode("SY");
    	        		if(zcTrayAndLocationEntity2 != null) {
    	        			//如果有，在此记录的tray_code(托盘码)字段后追加我在（4）生成的逻辑托盘码
    	        			String tray_code = zcTrayAndLocationEntity2.getTray_code();
    	        			tray_code = tray_code + addStr;
    	        			zcTrayAndLocationEntity2.setTray_code(tray_code);
    	        			aff = inventoryService.updateTrayLocationByID(zcTrayAndLocationEntity2);
    	        		}else {
    	        			//如果没有，则新增一条记录
    	        			ZcTrayAndLocationEntity zcTrayAndLocationEntity3 = new ZcTrayAndLocationEntity();
    	        			//托盘码
    	        			zcTrayAndLocationEntity3.setTray_code(addStr);
    	        			//库区编码
    	        			zcTrayAndLocationEntity3.setLocation_code("SY");
    	        			//绑定人
    	        			zcTrayAndLocationEntity3.setBinding_person(user.getId());
    	            		//绑定时间
    	        			zcTrayAndLocationEntity3.setBinding_date(sdf.format(new Date()));
    	        			aff = inventoryService.trayLocationInsert2(zcTrayAndLocationEntity3);
    	        		}
                    }//物料找不到库位
            	}//物料找不到托盘
            }//物料找不到托盘
		try {
			ResponseUtil.write(response, aff);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据盘点详情id查询复盘条码
	 * @author jyy
	 * @param invenId 盘点详情id
	 * @param response
	 */
	@RequestMapping("/queryCodeListByinvenId")
	public void queryCodeListByinvenId(Long invenId, HttpServletResponse response) {
		List<InventoryDetailCode> list = inventoryService.queryCodeListByinvenId(invenId);
		
		JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(list);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", list.size());
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 查询需抹平损益条码列表
	 * @param inventoryDetailCode 盘点明细条码实体
	 * @param response 响应	
	 * @param httpSession 回话
	 */
	@RequestMapping("/queryCodeList")
	public void queryCodeList(InventoryDetailCode inventoryDetailCode , HttpServletResponse response, HttpSession httpSession) {
		//仓库id
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		inventoryDetailCode.setWarehouse_id(warehouse_id);
		List<InventoryDetailCode> list = inventoryService.queryCodeList(inventoryDetailCode);
		int count = inventoryService.countCodeList(inventoryDetailCode);
		JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(list);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 根据条码抹平差异
	 * @param inventoryDetailCode
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/smoothing")
	public void smoothing(InventoryDetailCode inventoryDetailCode, HttpServletResponse response, HttpSession session) throws Exception {
		//获取session信息
		ZcSysUserEntity user = (ZcSysUserEntity)session.getAttribute("user");
		
		int aff = 0;
		//1.根据条码在 条码托盘表中找到对应的托盘，再根据托盘找到相对应的库位，将此托盘从SY库位中移除
		 //根据原条码查询绑定托盘的信息
	        ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = receiveDetailService.queryMaterielTrayByCode(inventoryDetailCode.getCode());
	        if(zcMaterielAndTrayEntity != null) {
	        	if(zcMaterielAndTrayEntity.getTray_code() != null) {
	        		 //根据托盘查询库位信息
	                ZcTrayAndLocationEntity zcTrayAndLocationEntity = receiveDetailService.queryTrayLocationByTray(zcMaterielAndTrayEntity.getTray_code());
					if(zcTrayAndLocationEntity != null) {
	                	 //在托盘库位表中去掉此托盘条码
	                    zcTrayAndLocationEntity.setTray_code(zcMaterielAndTrayEntity.getTray_code()+",");
	                    aff = carService.updateTrayCodeByid(zcTrayAndLocationEntity);
	                    //查询此托盘还有没有条码，没有则删除,或此库位还有没有托盘，没有则删除
	                    inventoryService.deleteEmptyTray();
	                }//物料找不到库位
	        	}//物料找不到托盘
	        }//物料找不到托盘
	        
	        //要移动的托盘码+“，”
	        String addStr = zcMaterielAndTrayEntity.getTray_code()+",";
	        
	    //2.将上述托盘条码追加到HC库位中
	      //在托盘-库位绑定表（zc_tray_location）中找是否存在 缓存区“HC”的记录
    		ZcTrayAndLocationEntity zcTrayAndLocationEntity2 = inventoryService.selectTrayLocationByLocationCode("HC");
    		if(zcTrayAndLocationEntity2 != null) {
    			//如果有，在此记录的tray_code(托盘码)字段后追加1步骤中查询到的托盘码
    			String tray_code = zcTrayAndLocationEntity2.getTray_code();
    			tray_code = tray_code + addStr;
    			zcTrayAndLocationEntity2.setTray_code(tray_code);
    			aff = inventoryService.updateTrayLocationByID(zcTrayAndLocationEntity2);
    		}else {
    			//如果没有，则新增一条记录
    			ZcTrayAndLocationEntity zcTrayAndLocationEntity3 = new ZcTrayAndLocationEntity();
    			//托盘码
    			zcTrayAndLocationEntity3.setTray_code(addStr);
    			//库区编码
    			zcTrayAndLocationEntity3.setLocation_code("HC");
    			//绑定人
    			zcTrayAndLocationEntity3.setBinding_person(user.getId());
        		//绑定时间
    			zcTrayAndLocationEntity3.setBinding_date(DateUtil.dateFormat3());
    			aff = inventoryService.trayLocationInsert2(zcTrayAndLocationEntity3);
    		}
		//3.在损溢表中将对应物料对应批次减去对应数量
    		aff = inventoryService.reduceNum(zcMaterielAndTrayEntity);
			//4.在缓存表中增加
    		ZcMaterileMoveInfoEntity zcMaterileMoveInfoEntity = new ZcMaterileMoveInfoEntity();
    		zcMaterileMoveInfoEntity.setMid(zcMaterielAndTrayEntity.getMid());
    		zcMaterileMoveInfoEntity.setEnterDate(DateUtil.dateFormat3());
    		zcMaterileMoveInfoEntity.setEnterPerson(user.getId());
    		zcMaterileMoveInfoEntity.setNum(zcMaterielAndTrayEntity.getmNum());
    		zcMaterileMoveInfoEntity.setPici(zcMaterielAndTrayEntity.getmBatch());
    		aff = zcBindAndUnbindService.inCache(zcMaterileMoveInfoEntity);
		//5.修改盘点详情条码表中的状态
    		inventoryDetailCode.setLocation_num("1");
    		aff =inventoryService.updateStateByCodeJyy(inventoryDetailCode);
    	//6.将结果返回给页面	
    		ResponseUtil.write(response, aff);
	} 
	//--------------------------------------------------------------------------------------------------------------------------
	
	
	/**
	 * 新增盘点单
	 * @param response
	 * @param inventoryOrder
	 */
	@RequestMapping("/addInventoryOrder")
	public void addInventoryOrder(HttpServletResponse response, InventoryOrder inventoryOrder, HttpSession session){
		
		//盘点状态：0未盘点
		inventoryOrder.setTab("0");

		//添加盘点单
		//-------------------llm start------------//
		Long affectRow = 0L;
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		if(warehouse_id != null || !"".equals(warehouse_id)){
			inventoryOrder.setWarehouse_id(warehouse_id);
			affectRow = inventoryService.addInventoryOrder(inventoryOrder);
		}
		//------------------llm end----------------//
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增盘点单详细
	 * @param response
	 * @param detail
	 */
	@RequestMapping("/addInventoryOrderDetail")
	public void addInventoryOrderDetail(HttpServletResponse response, InventoryDetail detail){
		detail.setTab(0);
		Long affectRow = inventoryService.addInventoryOrderDetail(detail);
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

 	/**
 	 * 根据ID删除该行数据
 	 * @param response
 	 * @param idArr
 	 */
	@RequestMapping("/deleteInventoryOrderById")
	public void deleteInventoryOrderById(HttpSession httpSession,HttpServletResponse response, @RequestParam("idArr[]") String[] idArr) throws Exception{
 		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		if(idArr.length > 0){
			for (int i = 0; i < idArr.length; i++) {
				
				 Map map = new HashMap();
				 map.put("id",Long.parseLong(idArr[i]));
				map.put("cancellation_time", df.format(new Date()));
				map.put("cancellation", userName);
				Integer affact = inventoryService.cacelpd(map);
				ResponseUtil.write(response, affact);
				map = null;
			}
		}
	}
	@RequestMapping("/restor")
	public void delet(HttpSession httpSession,HttpServletResponse response, @RequestParam("idArr[]") String[] idArr) throws Exception{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	       
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		if(idArr.length > 0){
			for (int i = 0; i < idArr.length; i++) {
				
				 Map map = new HashMap();
				 map.put("id", Long.parseLong(idArr[i]));
					map.put("restorer_time", df.format(new Date()));
					map.put("restorer", userName);
				Integer affact = inventoryService.restorpd(map);
				ResponseUtil.write(response, affact);
				map = null;
			}
		}
        
	}
	
	
 	/**
 	 * 根据盘点单详细ID删除订单信息
 	 * @param response
 	 * @param id 订单详细ID
 	 */

 	@RequestMapping("/deleteInventoryOrderDetailById")
	public void deleteInventoryOrderDetailById(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
 		if(idArr.length > 0){
 			for (int i = 0; i < idArr.length; i++) {
 	            Long affectRow = inventoryService.deleteInventoryOrderDetailById(Long.parseLong(idArr[i]));
 	            if (affectRow > AFFECT_ROW) {
 	                try {
						ResponseUtil.write(response, affectRow);
					} catch (Exception e) {
						e.printStackTrace();
					}
 	            } else {
 	                try {
						ResponseUtil.write(response, AFFECT_ROW);
					} catch (Exception e) {
						e.printStackTrace();
					}
 	            }
 	        }
 		}
	}
 	/**
 	 * 行内编辑盘点订单表
 	 * @param response
 	 * @param id 订单ID
 	 * @param fieldName 修改的字段名称
 	 * @param fieldValue 修改的字段的值
 	 */
 	@RequestMapping("/updateInventoryOrderById")
	public void updateInventoryOrderById(HttpServletResponse response, String id, String fieldName, String fieldValue){
		Long affectRow = inventoryService.updateInventoryOrderById(id, fieldName, fieldValue);
		if(affectRow > AFFECT_ROW){
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
 	 * 行内编辑盘点订单表详细
 	 * @param response
 	 * @param id 订单ID
 	 * @param fieldName 修改的字段名称
 	 * @param fieldValue 修改的字段的值
 	 */
 	@RequestMapping("/updateInventoryOrderDetailById")
	public void updateInventoryOrderDetailById(HttpServletResponse response, String mid, String fieldName, String fieldValue,String cid,String detailid){
		//System.out.println(mid+"**********gys"+cid);
 		Long affectRow = inventoryService.updateInventoryOrderDetailById(mid, fieldName, fieldValue,cid,detailid);
		if(affectRow > AFFECT_ROW){
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
 	
	/**
	 * 分页条件查询盘点单
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryInventoryOrderCriteria")
	public void queryInventoryOrderCriteria(HttpServletResponse response, LzQueryCriteria criteria, HttpSession session){
		String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        String keyword03 = criteria.getKeyword03();
        String keyword04 = criteria.getKeyword04();
        Long warehouse_id = (Long) session.getAttribute("warehouse_id");
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        if(keyword03 == null){
            keyword03 = "";
        }
        if(keyword04 == null && warehouse_id != null && !"".equals(warehouse_id)){
            keyword04 = warehouse_id.toString();
        }else{
        	keyword04 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        criteria.setKeyword03(keyword03);
        criteria.setKeyword04(keyword04);
        List<InventoryOrder> inventoryOrderList = inventoryService.queryInventoryOrderCriteria(criteria);
        int count = inventoryService.countInventoryOrderCriteria(criteria);
        
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(inventoryOrderList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("error,新增盘点单，给页面返回值，报错");
        }
	}
	
	/**
 	 * 根据订单编号查询订单详细
 	 * @param response
 	 * @param criteria 订单ID
 	 * @throws Exception
 	 */
 	@RequestMapping("/queryInventoryDetailCriteriaById")
	public void queryInventoryDetailCriteriaById(HttpServletResponse response, LzQueryCriteria criteria) throws Exception{
 		String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        List<InventoryDetail> inventoryDetailList = inventoryService.queryInventoryDetailCriteriaById(criteria);
        int count = inventoryService.countInventoryDetailCriteriaById(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(inventoryDetailList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
 	}
 	
 	/**
	 * 分页条件查询盘点单(Android)
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryInventoryOrderCriteriaAndroid")
	public void queryInventoryOrderCriteriaAndroid(HttpServletResponse response, String warehouse_id){
//        List<InventoryOrder> inventoryOrderList = inventoryService.queryInventoryOrderCriteriaAndroid();
		/*----------llm 修改，加参数 warehouse_id start -----------*/
		Long warehouseId = 0L;
		if(warehouse_id != null && !"".equals(warehouse_id)){
			warehouseId = Long.parseLong(warehouse_id);
		}
		List<InventoryOrder> inventoryOrderList = inventoryService.queryInventoryOrderCriteriaAndroid(warehouseId);
		/*----------llm 修改，加参数 warehouse_id end -----------*/
        JSONObject jsonObject = new JSONObject();
        if(inventoryOrderList.size() > AFFECT_ROW){
            jsonObject.put("status", "1");
            jsonObject.put("data", inventoryOrderList);
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "查询数据为空");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	/**
 	 * 根据盘点单号查询盘点详细(Android)
 	 * @param response
 	 * @param criteria 订单ID
 	 * @throws Exception
 	 */
 	@RequestMapping("/queryInventoryDetailCriteriaByIdAndroid")
	public void queryInventoryDetailCriteriaByIdAndroid(HttpServletResponse response, String order_id){
        List<InventoryDetail> inventoryDetailList = inventoryService.queryInventoryDetailCriteriaByIdAndroid(order_id);
        JSONObject jsonObject = new JSONObject();
        if(inventoryDetailList.size() > AFFECT_ROW){
            jsonObject.put("status", "1");
            jsonObject.put("data", inventoryDetailList);
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "查询数据为空");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
 	}
 	
 	/**
 	 * 复盘查询
 	 * 根据盘点单号查询盘点详细(Android)
 	 * @param response
 	 * @param criteria 订单ID
 	 * @throws Exception
 	 */
 	@RequestMapping("/queryInventoryDetailCriteriaByIdAndroid2")
	public void queryInventoryDetailCriteriaByIdAndroid2(HttpServletResponse response, String order_id){
        List<InventoryDetail> inventoryDetailList = inventoryService.queryInventoryDetailCriteriaByIdAndroid2(order_id);
        JSONObject jsonObject = new JSONObject();
        if(inventoryDetailList.size() > AFFECT_ROW){
            jsonObject.put("status", "1");
            jsonObject.put("data", inventoryDetailList);
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "查询数据为空");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
 	}
 	
 	
 	/**
 	 * 修改盘点单详细(Android)--盘点提交接口
 	 * @param response 响应
 	 * @param jsonValue  InventoryDetail 盘点详情实体集合
 	 * @param person 操作人
 	 * @param state 状态->1：初盘，2：复盘
 	 */
 	@RequestMapping("/updateInventoryDetailAndroid")
	public void updateInventoryDetailAndroid(HttpServletResponse response, String jsonValue, String person, String state) {
 		Gson gson = new Gson();
 		String tab = "0";
 		String status = "0";
 		int num = 0;
        List<InventoryDetail> inventoryDetailList = gson.fromJson(jsonValue,
                new TypeToken<List<InventoryDetail>>() {
                }.getType());
 		JSONObject jsonObject = new JSONObject();
 		if(inventoryDetailList.size() > AFFECT_ROW){
        	for (int i = 0; i < inventoryDetailList.size(); i++) {
        		/*获取传来的codeMark
        		List<CodeMark> codeList = inventoryDetailList.get(i).getReceiveCode();
        		int actual_quantity = 0;
        		for (CodeMark codeMark : codeList) {
        			actual_quantity+=codeMark.getNum();
				}
        		inventoryDetailList.get(i).setActual_quantity(Long.parseLong(actual_quantity+""));*/
        		
        		//二级详情账面库存
        		Long theoretical_quantity = inventoryDetailList.get(i).getTheoretical_quantity();
        		//TODO
        		//复盘数量
        		int check_num = inventoryDetailList.get(i).getCheck_num();
        		//复盘差异
        		inventoryDetailList.get(i).setCheck_diff(check_num - Integer.valueOf(theoretical_quantity+"")  );
        		//条码集合
        		List<InventoryDetailCode> inventoryDetailCodes = inventoryDetailList.get(i).getInventoryDetailCode();
        		
        		if("2".equals(state)) {
        			num = 2;
        			//复盘,把条码存入数据库
        			inventoryService.insertCodeInInventory(inventoryDetailCodes, inventoryDetailList.get(i).getOrder_id(), inventoryDetailList.get(i).getId());
        			/*for (InventoryDetailCode inventoryDetailCode : inventoryDetailCodes) {
        				//账面库存
        				int theory_num = inventoryDetailCode.getTheory_num();
        				//复盘数量
        				int reality_num = inventoryDetailCode.getReality_num();
        				//复盘差异
        				inventoryDetailCode.setDiff_num(theory_num - reality_num);
        				inventoryService.insert(inventoryDetailCode);
    				}*/
        			tab = "2";
        		}else {
        			num = 1;
        			//初盘
        			Long actual_quantity = inventoryDetailList.get(i).getActual_quantity();
        			//理论数量
        			//int count =inventoryService.selectKwCount(inventoryDetailList.get(i).getLocation_num());
        			InventoryDetail detail = inventoryService.queryInventoryDetailById2(inventoryDetailList.get(i).getId());
        			Long first = detail.getTheoretical_quantity();
            		inventoryDetailList.get(i).setTheoretical_quantity(first);
            		//出盘差异
            		Long difference = actual_quantity - first;
            		inventoryDetailList.get(i).setDifference_quantity(difference);
            		
            		//如果初盘差异为0，复盘差异也设置为0，解决处盘无差异，但复盘有差异数据的问题
            		if(inventoryDetailList.get(i).getDifference_quantity() == 0) {
            			inventoryDetailList.get(i).setCheck_diff(0);
            		}
            		
            		if(difference != 0){
            			//如果有差异
            			tab = "1";
            			status = "1";
            			inventoryDetailList.get(i).setTab(0);
            		}else{
            			tab = "3";
            			inventoryDetailList.get(i).setTab(1);
            		}
        		}
        		inventoryService.updateInventoryDetailAndroid(inventoryDetailList.get(i));
        		
        		//--------------给历史记录表插入数据--------------
        		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        		String time = format.format(new Date());
        		BarCodeOperation bar = new BarCodeOperation();
    			bar.setOperator(Long.parseLong(person));
    			bar.setMaterielId(inventoryDetailList.get(i).getMateriel_id());
    			bar.setOperatingTime(time);
    			bar.setType("盘点");
    			bar.setResult("成功");
    			for(InventoryDetailCode cm : inventoryDetailList.get(i).getInventoryDetailCode()){
    				ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(cm.getCode());
    				bar.setBatch(byCode.getPici());
    				bar.setBarCode(cm.getCode());
    				barCodeOperationService.insert(bar);
    			}
        		//--------------给历史记录表插入数据--------------
			}
//    		inventoryService.updateInventoryOrderById(inventoryDetailList.get(i).getOrder_id()+"", "tab", tab);
			InventoryOrder inventoryOrder = new InventoryOrder();
			if(num == 2) {
				//复盘人
				inventoryOrder.setChecked_man(Long.valueOf(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//复盘时间
				inventoryOrder.setChecked_time(sdf.format(new Date()));
			}else {
				//初盘人
				inventoryOrder.setInventory_man(Long.valueOf(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//初盘时间
				inventoryOrder.setInventory_time(sdf.format(new Date()));
			}
			if("1".equals(status)){
				tab = "1";
			}
			inventoryOrder.setTab(tab);
			inventoryOrder.setId(inventoryDetailList.get(0).getOrder_id());
			inventoryService.update(inventoryOrder);
			try {
				jsonObject.put("status", "1");
	            jsonObject.put("data", "提交成功");
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	try {
				jsonObject.put("status", "0");
	            jsonObject.put("message", "提交失败");
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
 	}
 	
 	/**
	 * 查询所有仓库
     * @throws Exception 
	 */
	@RequestMapping("/queryAllWarehouseAndroid")
	public void queryAllWarehouseAndroid(HttpServletResponse response) throws Exception{
		List<Warehouse> warehouseList = inventoryService.queryAllWarehouseAndroid();
		JSONObject jsonObject = new JSONObject();
        if(warehouseList.size() > AFFECT_ROW){
            jsonObject.put("status", "1");
            jsonObject.put("data", warehouseList);
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "查询数据为空");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	/**
 	 * 根据盘点单号查询盘点详情
 	 * @param orderId
 	 * @param response
 	 */
	@RequestMapping("/queryInventoryDetailByOrder")
 	public void queryInventoryDetailByOrder(String orderId,HttpServletResponse response) {
		if (!"".equals(orderId)) {
			List<InventoryDetail> inventoryDetailList = inventoryService.queryInventoryDetailByOrder(orderId);
	        JSONArray jsonArray = JSONArray.fromObject(inventoryDetailList);
	        JSONObject jsonObject = new JSONObject();
	        jsonObject.put("code", AFFECT_ROW);
	        jsonObject.put("data", jsonArray);
	        try {
	            ResponseUtil.write(response, jsonObject);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		} else {
			try {
				JSONObject jsonObject = new JSONObject();
		        jsonObject.put("code", AFFECT_ROW);
		        jsonObject.put("data", null);
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@ResponseBody
	@RequestMapping("/queryMidByOrder")
	public void queryOrder(String orderId,HttpServletResponse response) {
		if (!"".equals(orderId)) {
			List<InventoryDetail> inventoryDetailList = inventoryService.queryMaterielId(Long.parseLong(orderId));
	        JSONArray jsonArray = JSONArray.fromObject(inventoryDetailList);
	       
	        try {
		            ResponseUtil.write(response, jsonArray);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		}
	}
	/**
	 * 分页查询物料
	 * @Title:listPageMaterielByCustomerIdAndWarehouseId
	 * @param page 
	 * @param warehouseId 仓库ID
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/findAllMateriel")
	public void listPageMaterielByCustomerIdAndWarehouseId(Page page,  Materiel materiel, HttpServletResponse response){
		Map<String, Object> map = new HashMap<>();
		map.put("limit", page.getLimit());
		map.put("page", page.getPage());
		if(materiel.getCustomer_name()!=null&&!"".equals(materiel.getCustomer_name())) {
			map.put("gys", materiel.getCustomer_name());
		}else {
			map.put("gys", "");
		}
		if(materiel.getMateriel_name()!=null&&!"".equals(materiel.getMateriel_name())) {
			map.put("wlmc", materiel.getMateriel_name());
		}else {
			map.put("wlmc", "");
		}
		if(materiel.getMateriel_num()!=null&&!"".equals(materiel.getMateriel_num())) {
			map.put("wlbm", materiel.getMateriel_num());
		}else {
			map.put("wlbm", "");
		}
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(null, jsonConfig);
		int count = 0;
		List<Materiel> list = new ArrayList<Materiel>();

		count = materielService.countAllMC(map);
		list = materielService.queryAllMC(map);

		jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		//System.out.println(jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
 	 * 根据盘点详情单号查询盘点详情
 	 * @param id
 	 * @param response
 	 */
	@RequestMapping("/queryInventoryDetailById")
 	public void queryInventoryDetailById(String id,HttpServletResponse response) {
		 InventoryDetail inventoryDetail = inventoryService.queryInventoryDetailById(Long.parseLong(id));
	     JSONArray jsonArray = JSONArray.fromObject(inventoryDetail);
	     JSONObject jsonObject = new JSONObject();
	     jsonObject.put("data", jsonArray);
	        try {
	            ResponseUtil.write(response, jsonObject);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}
	/**
     * 导出Excel 现在使用导出方法2019-11-15 17:33:19
     * @param response
	 * @throws UnsupportedEncodingException 
     * @throws Exception
     */
    @RequestMapping("/doExportall")
    public void doExportall1(HttpServletResponse response, LzQueryCriteria criteria,HttpSession session){
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        String keyword03 = criteria.getKeyword03();
        String keyword04 = criteria.getKeyword04();
        Long warehouse_id = (Long) session.getAttribute("warehouse_id");
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        if(keyword03 == null){
            keyword03 = "";
        }
        if(keyword04 == null && warehouse_id != null && !"".equals(warehouse_id)){
            keyword04 = warehouse_id.toString();
        }else{
        	keyword04 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        criteria.setKeyword03(keyword03);
        criteria.setKeyword04(keyword04);
 		List<InventoryDetail> inventoryDetails = inventoryService.selectInventoryDetailByInventoryOrderCriteria(criteria);
	    LzQueryCriteria criteria1=new LzQueryCriteria();
        List<List<String>> lists;
		try {
			lists = zhuanlistX(inventoryDetails);
			ExcelUtils.export("盘点所有数据",namessX(), response, lists);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    }
    /**
     * 现在使用导出方法2019-11-15 17:33:19
     * @return
     */
    public List<String> namessX() {
        List<String> list = new ArrayList<>();
        list.add("序号");
        list.add("盘点单号");
        list.add("盘点类型");
        list.add("盘点人员");
        list.add("盘点日期");
        list.add("复盘人");
        list.add("复盘日期");
        list.add("确认人");
        list.add("确认日期");
        list.add("库位");
        list.add("盘点数量");
        return list;
    }
	/**
	 * 数据转换 现在使用导出方法2019-11-15 17:33:19
	 * @param inventoryDetails
	 * @return
	 * @throws UnsupportedEncodingException
	 */
    public List<List<String>> zhuanlistX(List<InventoryDetail> inventoryDetails) {
    	List<List<String>> lists = new ArrayList<>();
    	for (int i = 0; i < inventoryDetails.size(); i++) {
    		InventoryOrder inventoryOrder = inventoryDetails.get(i).getInventoryOrder();
		    if(null != inventoryOrder){
		    	List<String> list = new ArrayList<>();
		    	list.add(String.valueOf(i+1));
		    	list.add(inventoryOrder.getInventory_order_num());
		    	list.add(inventoryOrder.getInventory_type());
		    	list.add(inventoryOrder.getUserName());
		    	list.add(inventoryOrder.getInventory_time());
		    	list.add(inventoryOrder.getCheckedMan());
		    	list.add(inventoryOrder.getChecked_time());
		    	list.add(inventoryOrder.getConfirmedMan());
		    	list.add(inventoryOrder.getConfirmed_time());
		    	list.add(inventoryDetails.get(i).getLocation_num());
		    	list.add("");
		    	lists.add(list);
		    	list = null;
		    }
        }
        return lists;
    }
    
    /**
     * 导出Excel原来导出信息的方法
     * @param response
     * @throws UnsupportedEncodingException 
     * @throws Exception
     */
    //@RequestMapping("/doExportall")
    public void doExportall(HttpServletResponse response, LzQueryCriteria criteria){
    	String keyword01 = criteria.getKeyword01();
    	String keyword02 = criteria.getKeyword02();
    	String keyword03 = criteria.getKeyword03();
    	if(keyword01 == null){
    		keyword01 = "";
    	}
    	if(keyword02 == null){
    		keyword02 = "";
    	}
    	if(keyword03 == null){
    		keyword03 = "";
    	}
    	criteria.setKeyword01(keyword01);
    	criteria.setKeyword02(keyword02);
    	criteria.setKeyword03(keyword03);
    	criteria.setPage(1);
    	criteria.setLimit(10000);
    	List<InventoryOrder> inventoryOrderList = inventoryService.queryInventoryOrderCriteria(criteria);
    	LzQueryCriteria criteria1=new LzQueryCriteria();
    	List<List<String>> lists;
    	try {
    		lists = zhuanlist(inventoryOrderList,criteria1);
    		ExcelUtils.export("盘点所有数据",namess(), response, lists);
    	} catch (UnsupportedEncodingException e) {
    		e.printStackTrace();
    	}
    }

    public List<String> namess() {
        List<String> list = new ArrayList<>();
        list.add("序号");
        list.add("盘点单号");
        list.add("盘点类型");
        list.add("盘点人员");
        list.add("盘点日期");
        list.add("复盘人");
        list.add("复盘日期");
        list.add("确认人");
        list.add("确认日期");
      
        list.add("状态");
      
        list.add("是否取消");
        list.add("取消人");
        
        list.add("取消时间");
      
        list.add("恢复人");
        
        list.add("恢复时间");
        list.add("备注");
      
        return list;
    }

    public List<List<String>> zhuanlist ( List<InventoryOrder> inventoryOrderList, LzQueryCriteria criteria) throws UnsupportedEncodingException{
		
		{
        List<List<String>> lists = new ArrayList<>();
           for (InventoryOrder inventoryOrder : inventoryOrderList) {
		    List<String> list = new ArrayList<>();
             list.add(String.valueOf(inventoryOrder.getId()));
             list.add(inventoryOrder.getInventory_order_num());
             list.add(inventoryOrder.getInventory_type());
             list.add(inventoryOrder.getUserName());
             list.add(inventoryOrder.getInventory_time());
             list.add(inventoryOrder.getCheckedMan());
             list.add(inventoryOrder.getChecked_time());
             list.add(inventoryOrder.getConfirmedMan());
             list.add(inventoryOrder.getConfirmed_time());
             if(inventoryOrder.getTab().equals("0")) {
            	 
             list.add("未盘点");
             }else  if(inventoryOrder.getTab().equals("1")) {
            	 
             list.add("已盘点");
             }else  if(inventoryOrder.getTab().equals("2")) {
            	 
             list.add("已复盘");
             }else {
            	 list.add("已确认");
             }
          
             
             if(inventoryOrder.getFlag().equals("0")) {
            	 
             list.add("已取消");
             }else if(inventoryOrder.getFlag().equals("1")) {
            	 
             list.add("已恢复");
             }else {
                	 list.add("未操作");
            }
             list.add(inventoryOrder.getCancellation());
             list.add(inventoryOrder.getCancellation_time());
             list.add(inventoryOrder.getRestorer());
             list.add(inventoryOrder.getRestorer_time());
             list.add(inventoryOrder.getRemark());
             lists.add(list);
             List<String> listd = new ArrayList<>();
             listd.add("盘点单编号为"+inventoryOrder.getInventory_order_num()+"的盘点单详情表");
             lists.add(listd);
             List<String> listn = new ArrayList<>();
            listn.add("序号");
            listn.add("库位编号");
             listn.add("库存数量");
             listn.add("盘点数量");
             listn.add("差异数量");
            lists.add(listn);
            criteria.setKeyword01(String.valueOf(inventoryOrder.getId()));
     		criteria.setKeyword02("");
     		criteria.setPage(1);
     		criteria.setLimit(10000);
     	     List<InventoryDetail> inventoryDetailList = inventoryService.queryInventoryDetailCriteriaById(criteria);
            for (InventoryDetail detail : inventoryDetailList) {
            	 List<String> list1 = new ArrayList<>();
            	
            	   list1.add(String.valueOf(detail.getId()));
              
                 list1.add(detail.getLocation_num());
               
                 
                 list1.add(String.valueOf(detail.getTheoretical_quantity()));
                 list1.add(String.valueOf(detail.getActual_quantity()));
                 list1.add(String.valueOf(detail.getDifference_quantity()));
              
                 lists.add(list1);
                 list1 = null;
			}
            list = null;
        }
        return lists;
    }
}
}

